#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <errno.h>

#define PORT 8888          // 服务器端口
#define MAX_CLIENTS 100     // 最大客户端连接数
#define BUFFER_SIZE 1024    // 缓冲区大小

int main() {
    int server_fd, client_fd, max_fd, activity;
    struct sockaddr_in server_addr, client_addr;
    int client_sockets[MAX_CLIENTS];  // 保存客户端套接字
    char buffer[BUFFER_SIZE];
    fd_set read_fds, write_fds;       // 描述符集合
    socklen_t addr_len;

    // 初始化客户端套接字列表
    for (int i = 0; i < MAX_CLIENTS; i++) {
        client_sockets[i] = 0;
    }

    // 创建服务器套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址结构
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    // 绑定服务器地址和端口
    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 监听端口
    if (listen(server_fd, 5) < 0) {
        perror("listen failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }
    printf("服务器启动，监听端口 %d\n", PORT);

    while (1) {
        // 清空描述符集合
        FD_ZERO(&read_fds);
        FD_ZERO(&write_fds);

        // 添加服务器套接字到集合
        FD_SET(server_fd, &read_fds);
        max_fd = server_fd;

        // 添加客户端套接字到集合
        for (int i = 0; i < MAX_CLIENTS; i++) {
            if (client_sockets[i] > 0) {
                FD_SET(client_sockets[i], &read_fds);
                FD_SET(client_sockets[i], &write_fds);  // 检查可写状态
            }
            if (client_sockets[i] > max_fd) {
                max_fd = client_sockets[i];
            }
        }

        // 使用 select 检查活动套接字
        activity = select(max_fd + 1, &read_fds, &write_fds, NULL, NULL);
        if (activity < 0) {
            perror("select error");
            continue;
        }

        // 检查是否有新的连接
        if (FD_ISSET(server_fd, &read_fds)) {
            addr_len = sizeof(client_addr);
            if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addr_len)) < 0) {
                perror("accept failed");
                continue;
            }

            // 打印新连接信息
            printf("新连接: 套接字 %d, IP: %s, 端口: %d\n",
                   client_fd, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

            // 添加新连接到客户端列表
            for (int i = 0; i < MAX_CLIENTS; i++) {
                if (client_sockets[i] == 0) {
                    client_sockets[i] = client_fd;
                    break;
                }
            }
        }

        // 处理客户端消息
        for (int i = 0; i < MAX_CLIENTS; i++) {
            int sd = client_sockets[i];

            if (FD_ISSET(sd, &read_fds)) {
                int bytes_read = read(sd, buffer, BUFFER_SIZE);
                if (bytes_read == 0) {
                    // 客户端断开连接
                    addr_len = sizeof(client_addr);
                    getpeername(sd, (struct sockaddr *)&client_addr, &addr_len);
                    printf("客户端断开: IP: %s, 端口: %d\n",
                           inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
                    close(sd);
                    client_sockets[i] = 0;
                } else {
                    // 处理收到的数据
                    buffer[bytes_read] = '\0';
                    printf("来自套接字 %d 的消息: %s\n", sd, buffer);

                    // 如果套接字可写，回显消息给发送方
                    if (FD_ISSET(sd, &write_fds)) {
                        if (send(sd, buffer, bytes_read, 0) < 0) {
                            perror("send error");
                        }
                    } else {
                        printf("套接字 %d 不可写，无法发送数据\n", sd);
                    }
                }
            }
        }
    }

    return 0;
}
